<template>
	<view class="print-manage">
		<view class="connected">
			<view class="connected-left">
				<view class="title">{{ deviceInfo.name }}</view>
				<view class="status">{{ printerStatus }}</view>
			</view>
			<view class="connected-right" v-if="deviceInfo.deviceId" @click="onPrinterBut">{{ printerBut }}</view>
		</view>
		<view class="bluetooth-device">
			<view class="title-box">
				<text class="main-text">蓝牙设备</text>
				<text class="refresh" v-if="!isRefresh" @click="onRefresh">刷新</text>
				<u-loading v-else mode="circle" size="28" color="#2979ff"></u-loading>
			</view>
			<view class="device-list">
				<template v-for="item of deviceList">
					<view class="device-box" :key="item.deviceId">
						<view class="device">
							<u-icon name="scan" size="40"></u-icon>
							<view class="device-info">
								<view class="name main-text">{{ item.name }}</view>
								<view class="deviceId">{{ item.deviceId }}</view>
							</view>
						</view>
						<view>
							<u-button type="primary" shape="circle" size="mini" @click="onConnect(item)"
								v-if="item.printerStatus == '立即连接'">立即连接</u-button>
							<u-button shape="circle" size="mini" :disabled="true" v-else>{{ item.printerStatus }}</u-button>
						</view>
					</view>
				</template>
				<u-empty :show="!deviceList.length" mode="search" text="未查询到打印设备"></u-empty>
			</view>
		</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	// 蓝牙配置
	import Bluetooth from '@/common/print/bluetooth.js';
	let bluetooth = new Bluetooth();

	export default {
		data() {
			return {
				printerStatus: '已断开',
				printerBut: '重新连接',
				deviceInfo: {
					name: '未连接到打印设备',
				},
				deviceList: [],
				isRefresh: false,
				isConnect: false
			};
		},
		async onLoad() {
			const deviceInfo = uni.getStorageSync(bluetooth.deviceTitle) || '';
			// 如果之前连接过设备,就自动连接
			if (deviceInfo && deviceInfo.deviceId) {
				await this.onConnect(deviceInfo);
			}
			this.getDeviceList();
		},
		onUnload() {
			bluetooth.closeBLEConnection();
		},
		methods: {
			// 断开或重连
			onPrinterBut() {
				if (this.printerBut == '断开连接') {
					bluetooth.closeBLEConnection();
					this.printerStatus = '已断开';
					this.printerBut = '重新连接';
					this.isConnect = false;
					this.setPrinterStatus();
				} else {
					this.onConnect(this.deviceInfo);
				}
			},
			// 点击连接蓝牙
			async onConnect(val) {
				// 如果已连接设备先断开再连其他设备
				if (this.isConnect) {
					await bluetooth.closeBLEConnection();
				}
				bluetooth.deviceInfo = val;
				try {
					//1.链接设备
					await bluetooth.createBLEConnection();
					this.isConnect = true;
					// 停止搜索蓝牙
					bluetooth.stopBluetoothDevicesDiscovery();
					//2.寻找服务
					let services = await bluetooth.getBLEDeviceServices();
					await this.select_service(services[0]);
				} catch (e) {
					bluetooth.showToast('连接失败,请刷新后重试')
					console.log("e: " + JSON.stringify(e));
				}
			},
			//选中服务
			async select_service(res) {
				bluetooth.deviceInfo.serviceId = res.uuid;
				try {
					await bluetooth.getBLEDeviceCharacteristics();
					this.deviceInfo = bluetooth.deviceInfo;
					this.printerStatus = '已连接';
					this.printerBut = '断开连接';
					this.setPrinterStatus();
				} catch (e) {
					//TODO handle the exception
					console.log("e: " + JSON.stringify(e));
				}
			},
			// 修改蓝牙列表中蓝牙的状态
			setPrinterStatus() {
				this.deviceList.forEach(item => {
					if (item.deviceId === this.deviceInfo.deviceId) {
						item.printerStatus = this.printerStatus;
					} else {
						item.printerStatus = '立即连接';
					}
				});
			},
			// 刷新蓝牙设备列表
			onRefresh() {
				this.isRefresh = true;
				this.getDeviceList();
			},
			// 获取蓝牙设备列表
			getDeviceList() {
				const _this = this;
				uni.showLoading({
					title: '蓝牙搜索中'
				})
				// 开始搜寻附近的蓝牙外围设备
				uni.startBluetoothDevicesDiscovery({
					success: res => {
						// 监听寻找到新设备
						uni.onBluetoothDeviceFound(({
							devices
						}) => {
							console.log(devices, 789789789789);
							//不重复,就添加到deviceList中
							const isFind = _this.deviceList.some(item => item.deviceId === devices[0].deviceId);
							if (!isFind && devices[0].name.length > 0) {
								// 如果已经连接上设备时
								if (devices[0].deviceId === _this.deviceInfo.deviceId) {
									devices[0].printerStatus = '已连接';
								} else {
									devices[0].printerStatus = '立即连接';
								}
								if(devices[0].name=='Qsprinter')
								{
									_this.onConnect(devices[0]);
								}
								_this.deviceList.push(devices[0]);
							}
						});
						// 根据 uuid 获取处于已连接状态的设备。
						uni.getConnectedBluetoothDevices({
							success({
								devices
							}) {
								if (devices.length) {
									//不重复,就添加到deviceList中
									const isFind = _this.deviceList.some(item => item.deviceId === devices[0].deviceId);
									if (!isFind && devices[0].name.length > 0) {
										// 如果已经连接上设备时
										if (devices[0].deviceId === _this.deviceInfo.deviceId) {
											devices[0].printerStatus = '已连接';
										} else {
											devices[0].printerStatus = '立即连接';
										}
										_this.deviceList.push(devices[0]);
									}
								}
							}
						})
					},
					fail: err => {
						bluetooth.showToast('搜索蓝牙设备失败或暂无开启的蓝牙设备')
					}
				});
				setTimeout(() => {
					_this.isRefresh = false;
					bluetooth.stopBluetoothDevicesDiscovery();
				}, 10000)
			},
		}
	}
</script>
<style>
	page {
		background-color: #f3f4f6;
	}
</style>
<style lang="scss" scoped>
	.print-manage {
		font-size: 28rpx;
		padding: 20rpx;

		.main-text {
			color: #303133;
			font-weight: 600;
		}

		.connected {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			color: #ffffff;
			border-radius: 20rpx;
			background-color: #2979ff;

			&-left {
				.title {
					font-size: 32rpx;
				}

				.status {
					margin-top: 10rpx;
					font-size: 24rpx;
				}
			}
		}

		.bluetooth-device {
			margin-top: 20rpx;
			padding: 20rpx;
			border-radius: 20rpx;
			background-color: #ffffff;

			.title-box {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.refresh {
					color: #2979ff;
				}
			}

			.device-list {
				margin-top: 30rpx;

				.device-box {
					display: flex;
					justify-content: space-between;
					align-items: center;

					&+.device-box {
						margin-top: 50rpx;
					}

					.device {
						display: flex;
						justify-content: space-between;
						align-items: center;

						&-info {
							margin-left: 20rpx;

							.deviceId {
								color: #909399;
								font-size: 20rpx;
							}
						}
					}
				}
			}
		}
	}
</style>